package com.hex.liyue.usermodule.activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hex.liyue.LiYueApplication;
import com.hex.liyue.R;
import com.hex.liyue.commonmodule.activity.BaseActivity;
import com.hex.liyue.commonmodule.glide.GlideRoundTransform;
import com.hex.liyue.commonmodule.manager.HttpManager;
import com.hex.liyue.commonmodule.net.ResponseListener;
import com.hex.liyue.commonmodule.utils.FileUtis;
import com.hex.liyue.commonmodule.utils.StatusBarCompatUtils;
import com.hex.liyue.commonmodule.view.IosChoiceDialog;
import com.hex.liyue.nearmodule.bean.NearListBean;
import com.hex.liyue.usermodule.bean.MyPhotoBean;
import com.hex.liyue.usermodule.presenter.IMyPhotosView;
import com.hex.liyue.usermodule.presenter.MyPhototsPresenter;
import com.hex.liyue.usermodule.view.PhotoSelectDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by $cmm on 2016/6/23.
 * <p/>
 * 我的照片界面
 */
public class MyPhotoActivity extends BaseActivity implements IMyPhotosView {
    @Bind(R.id.iv_toobar_back)
    ImageView ivToobarBack;
    @Bind(R.id.tv_toobar_title)
    TextView tvToobarTitle;
    @Bind(R.id.tv_toobar_right)
    TextView tvToobarRight;
    @Bind(R.id.noScrollgridview)
    GridView noScrollgridview;


    private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果
    private List<MyPhotoBean.DataBean.UrlsBean> urlsBeen;
    private MyPhototsPresenter myPhototsPresenter;
    private GridAdapter gridAdapter;
    private File tempFile;

    @Override
    protected void bindPresenter() {
        myPhototsPresenter = new MyPhototsPresenter(this);
    }

    @Override
    protected void initData(Bundle extras) {
        myPhototsPresenter.getAddPhoto();
        tempFile = new File(FileUtis.getDirectory() + File.separator + System.currentTimeMillis() + "_userPhoto.png");
    }

    @Override
    public int getContentLayout() {
        return R.layout.activity_my_photos;
    }

    @Override
    protected void initToolbar() {
        StatusBarCompatUtils.compat(this);
        ivToobarBack.setVisibility(View.VISIBLE);
        tvToobarRight.setVisibility(View.VISIBLE);
        tvToobarRight.setText("上传");
        tvToobarTitle.setText("照片");
    }

    @Override
    public void setAdapter(final MyPhotoBean myPhotoBean) {
        urlsBeen = myPhotoBean.data.urls;
        gridAdapter = new GridAdapter(urlsBeen);
        noScrollgridview.setAdapter(gridAdapter);
        noScrollgridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == myPhotoBean.data.urls.size()) {
                    selectPhoto();
                }
            }
        });
        noScrollgridview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                if (position == myPhotoBean.data.urls.size()) {
                    return false;
                }
                IosChoiceDialog iosChoiceDialog = new IosChoiceDialog(MyPhotoActivity.this, "提示", "是否删除照片?");
                iosChoiceDialog.show();
                iosChoiceDialog.setOnButtonClickListener(new IosChoiceDialog.OnButtonClickListener() {
                    @Override
                    public void onOkClickListener() {
                        if (urlsBeen != null) {
                            deletePhoto(position);
                        }
                    }

                    @Override
                    public void onCancelClickListener() {

                    }
                });
                //删除图片
                return true;
            }
        });
        PersonEditActivity.falg = true;
    }

    /**
     * 这是一个删除照片的方法
     *
     * @param position
     */
    private void deletePhoto(final int position) {
        /**
         * 如果是本地文件的话直接删除
         */
        if (!TextUtils.isEmpty(urlsBeen.get(position).status)) {
            if (urlsBeen.get(position).status.equals("3")) {
                urlsBeen.remove(position);
                gridAdapter.notifyDataSetChanged();
                return;
            }
        }
        List<Integer> list = new ArrayList<>();
        if (!TextUtils.isEmpty(urlsBeen.get(position).file_id)){
            list.add(Integer.parseInt(urlsBeen.get(position).file_id));
        }
        HttpManager.getInstance().deleteUserPhotos(list, new ResponseListener<NearListBean>() {
            @Override
            public void onSuccess(NearListBean nearListBean) {
                urlsBeen.remove(position);
                gridAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(String responseresult) {
                showT(responseresult);
            }
        });

    }

    @Override
    public void closeCurrentActivity(int phototNum) {
        //上传完毕
        Intent intent = new Intent();
        intent.putExtra("phototNum", phototNum);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void setFinsh() {
        finish();
    }

    //弹出选择图片的框
    public void selectPhoto() {
        final PhotoSelectDialog selectDialog = new PhotoSelectDialog(MyPhotoActivity.this);
        selectDialog.setOnPhotoListener(new PhotoSelectDialog.OnPhotoListener() {
            @Override
            public void photo() {
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        "image/*");
                startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
            }

            @Override
            public void camera() {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra("camerasensortype", 2);// 调用前置摄像头
                intent.putExtra("autofocus", true);// 自动对焦
                intent.putExtra("fullScreen", false);// 全屏
                intent.putExtra("showActionIcons", false);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
                startActivityForResult(intent, PHOTO_REQUEST_TAKEPHOTO);
            }

            @Override
            public void cancel() {
                selectDialog.dismiss();
            }
        });
        selectDialog.show();
    }

    @OnClick({R.id.iv_toobar_back, R.id.tv_toobar_right})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_toobar_back:
                onBackPressed();
                break;
            case R.id.tv_toobar_right://上传图片
                myPhototsPresenter.getUpdatePhoto(urlsBeen);
                break;
        }
    }

    //裁剪
    private void startPhotoZoom(Uri uri, int size) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");

        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", size);
        intent.putExtra("outputY", size);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    //activity回调
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PHOTO_REQUEST_TAKEPHOTO:
                    startPhotoZoom(Uri.fromFile(tempFile), 300);
                    break;
                case PHOTO_REQUEST_GALLERY:
                    if (data != null) {
                        startPhotoZoom(data.getData(), 300);
                    }
                    break;
                case PHOTO_REQUEST_CUT:
                    if (data != null) {
                        MyPhotoBean.DataBean.UrlsBean bean = new MyPhotoBean.DataBean.UrlsBean();
                        bean.url = tempFile.getAbsolutePath();//本地图片
                        bean.status = "3";
                        urlsBeen.add(bean);
                        gridAdapter.notifyDataSetChanged();
                        tempFile = new File(FileUtis.getDirectory() + File.separator + System.currentTimeMillis() + "_userPhoto.png");
                        break;
                    }
                    break;
            }
        }
    }

    @Override
    public void showLod(String msg) {
        showLoad(this, msg);
    }

    @Override
    public void closeLod() {
        closeLoad();
    }

    @Override
    public void showT(String msg) {
        showToast(this, msg);
    }

    public class GridAdapter extends BaseAdapter {
        public List<MyPhotoBean.DataBean.UrlsBean> list;

        public GridAdapter(List<MyPhotoBean.DataBean.UrlsBean> list) {
            this.list = list;
        }

        public int getCount() {
            if (list.size() < 6) {// 1 2 3 4 5
                return list.size() + 1;
            } else {
                return list.size();
            }
        }

        public MyPhotoBean.DataBean.UrlsBean getItem(int arg0) {
            return list.get(arg0);
        }

        public long getItemId(int arg0) {
            return arg0;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(LiYueApplication.getInstance(), R.layout.item_published_grida, null);
                holder = new ViewHolder();
                holder.image = (ImageView) convertView
                        .findViewById(R.id.item_grida_image);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            if (position == list.size()) {
                Glide.with(LiYueApplication.getInstance())
                        .load(R.drawable.icon_addpic_unfocused)
                        .transform(new GlideRoundTransform(LiYueApplication.getInstance()))
                        .error(R.drawable.default_error_image)
                        .into(holder.image);
                if (position == 9) {
                    holder.image.setVisibility(View.GONE);
                }
            } else {
                MyPhotoBean.DataBean.UrlsBean urlsBean = list.get(position);
                if (urlsBean.file_id == null) {
                    Glide.with(LiYueApplication.getInstance())
                            .load(new File(urlsBean.url))
                            .transform(new GlideRoundTransform(LiYueApplication.getInstance()))
                            .error(R.drawable.default_error_image)
                            .into(holder.image);
                } else {
                    Glide.with(LiYueApplication.getInstance())
                            .load(urlsBean.url)
                            .transform(new GlideRoundTransform(LiYueApplication.getInstance()))
                            .error(R.drawable.default_error_image)
                            .into(holder.image);
                }

            }

            return convertView;
        }

        public class ViewHolder {
            public ImageView image;
        }

    }
}

